import logging
import time
from logging import handlers
from utils import get_config as con

configs = con.configs


class MyLogger(object):
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL
    }

    def __init__(self, class_name=__name__, file_name=configs['project_path'] + configs['log_path'] + 'loginfo.log',
                 log_level=configs['log']['file_level'], when='D',
                 back_count=3, pattern=configs['log']['pattern']):

        self.log_level = log_level
        self.pattern = pattern
        self.class_name = class_name
        self.back_count = back_count
        self.when = when
        self.file_name = file_name


    @property
    def mylogger(self):
        self.logger = logging.getLogger(self.class_name)
        if not self.logger.handlers:
            # print('测试路径：' + self.file_name + ',level:' + self.log_level)
            format_str = logging.Formatter(self.pattern)  # 设置日志格式
            self.logger.setLevel(self.level_relations.get(self.log_level))
            # self.logger.propagate = False
            sh = logging.StreamHandler()  # 往屏幕上输出
            sh.setFormatter(format_str)  # 设置屏幕输出格式
            th = logging.handlers.TimedRotatingFileHandler(filename=self.file_name, when=self.when,
                                                           backupCount=self.back_count,
                                                           encoding='utf-8')  # 往文件写入日志，每星期（一）自动生成文件
            th.setFormatter(format_str)  # 设置文件写入格式
            self.logger.addHandler(sh)
            self.logger.addHandler(th)
        return self.logger


def output_format(info, text):
    time1 = format_time('%Y-%m-%d %H:%M:%S')
    prt = time1 + ' -[' + info.upper() + ']- ' + text
    return prt


def format_time(datafmt):
    time1 = time.strftime(datafmt, time.localtime(time.time()))
    return time1


# 日志对象
info_log = MyLogger(file_name=configs['project_path'] + configs['log_path'] + 'loginfo.log', log_level='info', class_name='info').mylogger
err_info = MyLogger(file_name=configs['project_path'] + configs['log_path'] + 'errorinfo.log', log_level='error', class_name='error').mylogger

if __name__ == '__main__':
    pass
